﻿using MotionControl.Modules.LightSource.LightControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Media.Media3D;

namespace MotionControl.Modules.LightSource.Models
{
    public class LightList : ObservableCollection<Light>
    {
        public static LightList GetInstance { get => _instance; }

        private static LightList _instance;
        static LightList()
        {
            ReadFromJsonFile();
        }

        //private LightList() {
        //var light1 = new Light("COM1", LightType.OPT, 2);            
        //Add(light1);
        //light1.AddChannel(new Channel(1, 0, "TOP_L1"));
        //light1.AddChannel(new Channel(2, 0, "TOP_L2"));
        ////light1.Channels.Add(new Channel(light3, 0, "TOP_R1"));
        ////light1.Channels.Add(new Channel(light4, 0, "TOP_R2"));
        ////light1.Channels.Add(new Channel(light5, 0, "TOP_背景光"));
        //var light2 = new Light("COM2", LightType.OPT, 2);
        //Add(light2);
        //light2.AddChannel(new Channel(1, 0, "BOT_L1"));
        //light2.AddChannel(new Channel(2, 0, "BOT_L2"));
        //light2.Channels.Add(new Channel(3, 0, "BOT_R1"));
        //light2.Channels.Add(new Channel(4, 0, "BOT_R2"));
        //light2.Channels.Add(new Channel(5, 0, "BOT_背景光"));
        //SaveToJsonFile();
        //}

        private const string jsonFilePath = "data/light.json";
        private static void ReadFromJsonFile()
        {
            try
            {
                string jsonFromFile = File.ReadAllText(jsonFilePath);
                _instance = JsonConvert.DeserializeObject<LightList>(jsonFromFile);
                foreach (var light in _instance)
                    light.ConnectChannelToLight();
                //for (int i = 0; i < deserializedList.Count; i++)
                //{
                //    Items[i] = deserializedList[i];
                //}
            }
            catch (Exception ex)
            {
            }
        }
        public void SaveToJsonFile()
        {
            try
            {
                JsonSerializer serializer = new JsonSerializer();
                string strFloats = JsonConvert.SerializeObject(this.ToList(), Formatting.Indented);
                File.WriteAllText(jsonFilePath, strFloats);
            }
            catch (Exception ex)
            {
            }
        }
    }
}
